package cn.zhentao.controller;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Objects;
import java.util.UUID;

/**
 * 离线 本地 TXT文件 语音朗读，生成mp3文件
 */
public class VoiceReading {
    public static void main(String[] args) {
        //本地TXT文件位置
        String text = textToStr("D:\\a1/111.txt");
        textToSpeechIO(text);
    }
            

        /**
         * 字符串文本转 wav格式 语音文件
         * @param text 要读的文字字符串
         */
        public static void textToSpeechIO(String text){
             String path = "D:\\a1/video";

            ActiveXComponent ax = null;
            Dispatch spFileStream = null;
            Dispatch spAudioFormat = null;
            Dispatch spVoice = null;
            try{
                ax = new ActiveXComponent("Sapi.SpFileStream");
                spFileStream = ax.getObject();

                ax = new ActiveXComponent("Sapi.SpAudioFormat");
                spAudioFormat = ax.getObject();

                spVoice = new ActiveXComponent("Sapi.SpVoice").getObject();
                // 设置音频流格式
                Dispatch.put(spAudioFormat, "Type", new Variant(22));
                // 设置文件输出流格式
                Dispatch.putRef(spFileStream, "Format", spAudioFormat);
                //随机uuid
                String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
//                String filePath = path + uuid + ".wav";
                String filePath = path + uuid + ".mp3";

                // 调用输出 文件流打开方法，创建一个.wav文件
//                Dispatch.call(spFileStream, "Open", new Variant("D:\\workspace3\\test/test.mp3"), new Variant(3), new Variant(true));
                Dispatch.call(spFileStream, "Open", new Variant(filePath), new Variant(3), new Variant(true));
                // 设置声音对象的音频输出流为输出文件对象
                Dispatch.putRef(spVoice, "AudioOutputStream", spFileStream);
                // 设置音量  0 ~ 100
                Dispatch.put(spVoice, "Volume", new Variant(100));
                // 设置朗读速度  -10 ~ +10
                Dispatch.put(spVoice, "Rate", new Variant(1));

                Dispatch.call(spVoice, "Speak", new Variant(text));

//                打印输出文件位置
                System.out.println(filePath);

                System.out.println("输出语音文件成功！");
            }catch(Exception e){
                e.printStackTrace();
            }finally {
                // 关闭输出文件
                Dispatch.call(Objects.requireNonNull(spFileStream), "Close");
                Dispatch.putRef(Objects.requireNonNull(spVoice), "AudioOutputStream", null);

                Objects.requireNonNull(spAudioFormat).safeRelease();
                spFileStream.safeRelease();
                spVoice.safeRelease();
                ax.safeRelease();
            }
        }

        /**
         * 生成语音文件并返回文件路径 - 专为AI回答语音播报设计
         * @param text 要转换为语音的文本
         * @return 生成的语音文件路径，失败时返回null
         */
        public static String generateVoiceFile(String text) {
            if (text == null || text.trim().isEmpty()) {
                System.err.println("❌ 语音播报文本为空");
                return null;
            }

            // 语音文件存储路径
            String basePath = "D:\\a1/voice/";

            // 确保目录存在
            java.io.File directory = new java.io.File(basePath);
            if (!directory.exists()) {
                boolean created = directory.mkdirs();
                if (!created) {
                    System.err.println("❌ 无法创建语音文件目录: " + basePath);
                    return null;
                }
                System.out.println("✅ 语音文件目录创建成功: " + basePath);
            }

            // 检查目录权限
            if (!directory.canWrite()) {
                System.err.println("❌ 语音文件目录没有写权限: " + basePath);
                return null;
            }

            ActiveXComponent ax = null;
            Dispatch spFileStream = null;
            Dispatch spAudioFormat = null;
            Dispatch spVoice = null;
            String filePath = null;

            try {
                System.out.println("🎵 开始生成语音文件...");

                ax = new ActiveXComponent("Sapi.SpFileStream");
                spFileStream = ax.getObject();

                ax = new ActiveXComponent("Sapi.SpAudioFormat");
                spAudioFormat = ax.getObject();

                spVoice = new ActiveXComponent("Sapi.SpVoice").getObject();

                // 设置音频流格式
                Dispatch.put(spAudioFormat, "Type", new Variant(22));
                // 设置文件输出流格式
                Dispatch.putRef(spFileStream, "Format", spAudioFormat);

                // 生成唯一文件名
                String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
                filePath = basePath + "ai_voice_" + uuid + ".mp3";

                // 创建语音文件
                Dispatch.call(spFileStream, "Open", new Variant(filePath), new Variant(3), new Variant(true));

                // 设置声音对象的音频输出流为输出文件对象
                Dispatch.putRef(spVoice, "AudioOutputStream", spFileStream);

                // 设置音量 0 ~ 100
                Dispatch.put(spVoice, "Volume", new Variant(85));

                // 设置朗读速度 -10 ~ +10 (稍微慢一点，更清晰)
                Dispatch.put(spVoice, "Rate", new Variant(0));

                // 执行语音合成
                Dispatch.call(spVoice, "Speak", new Variant(text.trim()));

                System.out.println("✅ 语音文件生成成功: " + filePath);

                // 验证文件是否真的生成了
                File generatedFile = new File(filePath);
                if (generatedFile.exists() && generatedFile.length() > 0) {
                    System.out.println("✅ 语音文件验证成功，文件大小: " + generatedFile.length() + " bytes");
                    return filePath;
                } else {
                    System.err.println("❌ 语音文件生成失败，文件不存在或为空");
                    return null;
                }

            } catch (Exception e) {
                System.err.println("❌ 生成语音文件失败: " + e.getMessage());
                e.printStackTrace();
                return null;
            } finally {
                try {
                    // 安全关闭资源
                    if (spFileStream != null) {
                        Dispatch.call(spFileStream, "Close");
                    }
                    if (spVoice != null) {
                        Dispatch.putRef(spVoice, "AudioOutputStream", null);
                    }
                    if (spAudioFormat != null) {
                        spAudioFormat.safeRelease();
                    }
                    if (spFileStream != null) {
                        spFileStream.safeRelease();
                    }
                    if (spVoice != null) {
                        spVoice.safeRelease();
                    }
                    if (ax != null) {
                        ax.safeRelease();
                    }
                } catch (Exception e) {
                    System.err.println("⚠️ 释放资源时出现异常: " + e.getMessage());
                }
            }
        }

        /**
         * txt文件转字符串
         * @param fileName txt文件所在位置
         * @return txt文件中的字符串
         */
        public static String textToStr(String fileName){
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new FileReader(fileName));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line=reader.readLine()) != null){
                    sb.append(line);
                }
                return sb.toString();
            } catch (IOException e) {
                e.printStackTrace();
                return "";
            }finally {
                try {
                    Objects.requireNonNull(reader).close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
    
    /**
         * 字符串文本阅读
         * @param str 要读的文字字符串
         */
        public static void readStr(String str){
            ActiveXComponent ax = new ActiveXComponent("Sapi.SpVoice");
            //运行时输出语音内容
            Dispatch spVoice = ax.getObject();
            //设置音量 0 ~ 100
            ax.setProperty("Volume",new Variant(100));
            //设置朗读速度 -10 ~ +10
            ax.setProperty("Rate",new Variant(1));
            //执行朗读
            Dispatch.call(spVoice,"Speak",new Variant(str));
        }


}

